
from django.shortcuts import render
import random
# Create your views here.
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from celery_tasks.sms.tasks import sms

# url('^image_codes/(?P<image_code_id>[\w-]+)/$', views.ImageCodeView.as_view()),
from rest_framework.views import APIView

from meiduo_mall.libs.yuntongxun.sms import CCP


class SMSCodeView(APIView):
    """
    短信验证码
    """

    def get(self, request, mobile):

        # 生成短信验证码
        sms_code = "%06d" % random.randint(0, 999999)

        # 创建和redis数据库的链接对象
        conn = get_redis_connection('verify')

        # 获取用户发送短信的时间间隔, 判断用户是否是重复发送
        send_flag = conn.get('sms_code_%s' % mobile)
        if send_flag:
            return Response({'message': '发送短信过于频繁'}, status=status.HTTP_401_UNAUTHORIZED)

        # 发送短信并储存数据 由于储存数据的时候 每一次都回去调用一次redis数据库, 所以用redis管道去连接, 一次就行了
        # conn.setex('sms_code_%s' % mobile, 300, sms_code)
        # conn.setex('send_flag_$s' % mobile, 60, '1')
        pl = conn.pipeline()
        pl.setex('sms_code_%s' % mobile, 300, sms_code)
        pl.setex('send_flag_%s' % mobile, 60, 1)

        # 执行execute一次性添加到数据库
        pl.execute()

        # ccp=CCP()
        # ccp.send_template_sms(mobile, [sms_code, '5'], 1)

        sms.delay(mobile, sms_code)
        print(sms_code)

        # 返回响应
        return Response({'message':'ok'})